package com.ruoyi.verify.controller;

import com.alibaba.fastjson.JSON;
import com.google.api.client.util.ArrayMap;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.feign.RemoteMenuService;
import com.ruoyi.verify.domain.*;
import com.ruoyi.verify.mapper.VerifyTemplateContentMapper;
import com.ruoyi.verify.service.*;
import com.ruoyi.verify.transform.VerifyPlanInfos;
import com.ruoyi.verify.transform.VerifyPlanMemberInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("verifyplaninfo")
public class VerifyPlanInfoController extends BaseController
{

    @Autowired
    private IVerifyPlanInfoService verifyPlanInfoService;

    @Autowired
    private IVerifyMemberInfoService verifyMemberInfoService;

    @Autowired
    private IVerifyTemplateService verifyTemplateService;


    @Autowired
    private IVerifyTemplateContentService verifyTemplateContentService;

    @Autowired
    private IVerifyRequirementService verifyRequirementService;


//    /**
//     * 获取某个计划详情
//     * 更新 by 2020/10/28 22:30
//     */
//    @GetMapping("get/{planid}")
//    public R get(@PathVariable("planid") Long planid)
//    {
//        String memberid = ServletUtils.getRequest().getHeader(Constants.CURRENT_ID);
//        VerifyPlanInfo verifyPlanInfo = verifyPlanInfoService.selectVerifyPlanInfoById(planid);
//        String operation = "Read";
//        if(verifyPlanInfo.getStatus()==0 && ifhaveauthority(verifyPlanInfo.getPlanid())){  //只有组长或者管理员可以编辑未发布的计划
//            operation = "Writed";
//        }
//
//        List<VerifyPlanInfo> verifyPlanInfos = verifyPlanInfoService.selectVerifyPlanInfoByParentId(planid);
//        Long groupleaderid = verifyPlanInfo.getGroupleaderid();
//
//        verifyPlanInfos.stream().forEach(vpi -> {
//            if(vpi.getSupplycategory()!=null){
//                vpi.setSupplycategorys(vpi.getSupplycategory().split(","));
//            }
//            VerifyQuestionnaire verifyQuestionnaire = new VerifyQuestionnaire();
//            verifyQuestionnaire.set(vpi.getSuppliername());
//            verifyQuestionnaire.setPlanid(planid.toString());
//            verifyQuestionnaire.setLoguser(memberid);
//            if(vpi.getGlobalcommit().equals(1l)){
//                vpi.setCurrentcommited("已提交");
//            }else {
//                if(verifyTemplateContentService.checkCommit(verifyQuestionnaire)){
//                    vpi.setCurrentcommited("已提交");
//
//                }else {
//                    vpi.setCurrentcommited("未提交");
//                }
//            }
//
//        });
//
//        List<VerifyMemberInfo> verifyMemberInfos1 = verifyMemberInfoService.selectVerifyMemberInfoByPlanid(planid);
//        VerifyPlanMemberInfo verifyPlanMemberInfo = new VerifyPlanMemberInfo();
//
//        verifyPlanMemberInfo.setVerifyPlanInfo(verifyPlanInfo);
//        verifyPlanMemberInfo.setVerifyPlanInfos(verifyPlanInfos);
//
//        List<VerifyPlanMemberInfo.innerVerify> innerVerifyList = verifyMemberInfos1.stream().map(vpi -> {
//            List<String> moudles = Arrays.asList(vpi.getMoudlecode().split(","));
//            if(groupleaderid!=null){
//                if(groupleaderid.equals(vpi.getMemberid())){
//                    vpi.setIsGroupLeader("1");
//                }
//                else {
//                    vpi.setIsGroupLeader("0");
//                }
//            }
//            VerifyPlanMemberInfo.innerVerify innerVerify = new VerifyPlanMemberInfo.innerVerify(vpi.getPlanid(), vpi.getMemberid(), moudles,vpi.getMembername(),vpi.getPhonenumber(),vpi.getJobnumber(),vpi.getJobunit(),vpi.getPosition(),vpi.getIsGroupLeader());
//            return innerVerify;
//        }).collect(Collectors.toList());
//
//        verifyPlanMemberInfo.setVerifyplanmembermoudle(innerVerifyList);
//        verifyPlanMemberInfo.setOperation(operation);
//
//        List<VerifyPlanMemberInfo> list = new ArrayList<VerifyPlanMemberInfo>();
//        list.add(verifyPlanMemberInfo);
//        return jacResult(list);
//    }



    /**
     * 查询审核计划列表
     */
    @GetMapping("list")
    public R list(VerifyPlanInfo verifyPlanInfo)
    {
        startPage();
        return result(verifyPlanInfoService.selectVerifyPlanInfoList(verifyPlanInfo));
    }

    /**
     * 我的计划页面 计划列表
     */
    @GetMapping("mylist")
    public R mylist(VerifyPlanInfo verifyPlanInfo)
    {
        String memberid = ServletUtils.getRequest().getHeader(Constants.CURRENT_ID);
        List<Long> longs = verifyPlanInfoService.selectMyVerifyPlanList(verifyPlanInfo, memberid);
        startPage();
        List<VerifyPlanInfo> verifyPlanInfos = verifyPlanInfoService.selectMyVerifyPlanInfoList(verifyPlanInfo, longs);
        if(verifyPlanInfos==null || verifyPlanInfos.size()==0){
            return R.ok();
        }
        return result(verifyPlanInfos);
    }


    /**
     * 新增保存【请填写功能名称】
     */
    @PostMapping("save")
    public R addSave(@RequestBody VerifyPlanInfo verifyPlanInfo)
    {
        verifyPlanInfo.setSource(1l);
        return toAjax(verifyPlanInfoService.insertVerifyPlanInfo(verifyPlanInfo));
    }

    /**
     * 修改保存【请填写功能名称】
     */
    @PostMapping("update")
    public R editSave(@RequestBody VerifyPlanInfo verifyPlanInfo)
    {
        return toAjax(verifyPlanInfoService.updateVerifyPlanInfo(verifyPlanInfo));
    }

    /**
     * 删除${tableComment}
     */
    @PostMapping("remove")
    public R remove(String ids)
    {
        return toAjax(verifyPlanInfoService.deleteVerifyPlanInfoByIds(ids));
    }

    /**
     * 计划发布、取消、失效
     */
    @PostMapping("modifyplanstatus")
    @Transactional(rollbackFor = Exception.class)
    public R publishplan(@RequestBody VerifyPlanInfo[] vpis){
        for(VerifyPlanInfo v:vpis){
//            VerifyPlanInfo verifyPlanInfo = new VerifyPlanInfo();
//            verifyPlanInfo.setPlanid(v.getPlanid());
//            verifyPlanInfo.setStatus(v.getStatus());
            List<VerifyPlanInfo> sonvpis = verifyPlanInfoService.selectVerifyPlanInfoByParentId(v.getPlanid());
            VerifyPlanInfo parentPlanInfo = verifyPlanInfoService.selectVerifyPlanInfoById(v.getPlanid());

            if(parentPlanInfo.getStatus().equals(4l) && v.getStatus().equals(2l)){
                return R.error("不可以取消已经开始的计划！");
            }if(parentPlanInfo.getStatus().equals(4l) && v.getStatus().equals(1l)){
                return R.error("不可以重复发布计划！");
            }
            if(!parentPlanInfo.getStatus().equals(4l) && v.getStatus().equals(3l)){
                return R.error("只可以失效审核中的计划！");
            }
            verifyPlanInfoService.updateVerifyPlanInfo(v); //修改计划状态
            if(v.getStatus().equals(1l)){ //发布计划
                for(VerifyPlanInfo s:sonvpis){
                    VerifyQuestionnaire verifyQuestionnaire = new VerifyQuestionnaire();
                    verifyQuestionnaire.setVendorname(s.getSuppliername());
                    verifyQuestionnaire.setVendorcode(s.getSuppliercode());
                    verifyQuestionnaire.setPlanid(s.getPlanid().toString());
                    verifyQuestionnaire.setVerifytype(s.getVerifytype());
                    verifyRequirementService.updateVerifyRequirementStatus(s.getPlanid(),4l);//审核需求状态变为计划发布
                    verifyTemplateService.insertQuestionnaire(verifyQuestionnaire,s.getFactorycode());
                }
            }else if(v.getStatus().equals(2l)){ //取消计划，此时需要判断审核是否已经开始
                for(VerifyPlanInfo s:sonvpis){
                    verifyRequirementService.updateVerifyRequirementStatus(s.getPlanid(),5l);//审核需求状态变为计划取消，此时可以生成计划
                }
            }else if(v.getStatus().equals(4l)){//开始计划
                for(VerifyPlanInfo s:sonvpis){
                    verifyRequirementService.updateVerifyRequirementStatus(s.getPlanid(),6l);//审核需求状态变为审核中
                }
            }else if(v.getStatus().equals(3l)){//失效计划
                for(VerifyPlanInfo s:sonvpis){
                    verifyRequirementService.updateVerifyRequirementStatus(s.getPlanid(),8l);//审核需求状态变为计划失效
                }
            }

        }

        return R.ok();
    }

    /**
     * 计划发布、取消、失效
     */
    @PostMapping("modifysonplanstatus")
    @Transactional(rollbackFor = Exception.class)
    public R publishsonplan(@RequestBody VerifyPlanInfo v){

//            VerifyPlanInfo verifyPlanInfo = new VerifyPlanInfo();
//            verifyPlanInfo.setPlanid(v.getPlanid());
//            verifyPlanInfo.setStatus(v.getStatus());
//            List<VerifyPlanInfo> sonvpis = verifyPlanInfoService.selectVerifyPlanInfoByParentId(v.getPlanid());
            VerifyPlanInfo currentSonplaninfo = verifyPlanInfoService.selectVerifyPlanInfoById(v.getPlanid());
            List<VerifyPlanInfo> allsonplaninfos = verifyPlanInfoService.selectVerifyPlanInfoByParentId(currentSonplaninfo.getParentid());


        if(currentSonplaninfo.getStatus().equals(4l) && v.getStatus().equals(2l)){
                return R.error("不可以取消已经开始的计划！");
            }if(v.getStatus().equals(1l)){
                return R.error("不可以发布子计划！");
            }
            if(!currentSonplaninfo.getStatus().equals(4l) && v.getStatus().equals(3l)){
                return R.error("只可以失效审核中的计划！");
            }
            verifyPlanInfoService.updateVerifyPlanInfo(v); //修改计划状态

            if(v.getStatus().equals(2l)){ //取消计划，此时需要判断审核是否已经开始
                    verifyRequirementService.updateVerifyRequirementStatus(v.getPlanid(),5l);//审核需求状态变为计划取消，此时可以生成计划
            }else if(v.getStatus().equals(4l)){//开始计划
                    verifyRequirementService.updateVerifyRequirementStatus(v.getPlanid(),6l);//审核需求状态变为审核中
            }else if(v.getStatus().equals(3l)){//失效计划
                    verifyRequirementService.updateVerifyRequirementStatus(v.getPlanid(),8l);//审核需求状态变为计划失效
            }



        return R.ok();
    }

    public boolean ifhaveauthority(Long planid){

        HttpServletRequest request = ServletUtils.getRequest();
        String tmpUserKey = request.getHeader(Constants.CURRENT_ID);

        if (Optional.ofNullable(tmpUserKey).isPresent())
        {
            Long userId = Long.valueOf(tmpUserKey);
            if (userId == 1L || verifyPlanInfoService.isgroupleader(userId,planid))
            {
                return true;
            }

            String s1 = verifyPlanInfoService.selectPermsByUserId(userId).stream().filter(s -> s!=null).filter(s -> s.equals("auditing:verifyplan:manager")).findAny().orElse(null);
            return s1!=null?true:false;
        }
        return false;
    }



    /**
     * 修改后 2020/11/10
     * 根据审核需求生成计划
     */
    @PostMapping("createverifyplanbyrequirement")
    @Transactional(rollbackFor = Exception.class)
    public R createVerifyPlan(@RequestBody Map<String,List<Long>> verifyrequirementids)
    {
        Map<String, Object> res = verifyPlanInfoService.createVerifyPlanByRequirementIds(verifyrequirementids.get("verifyrequirementids"));
        if(res==null){
            return R.error();
        }else if(res.containsKey("errMsg")==true){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(505,res.get("errMsg").toString());
        }

        return resultMap(res);
    }

    /**
     * 根据计划id获取计划详情
     */
    /**
     * 获取某个计划详情
     * 更新 2020/11/11
     */
    @GetMapping("getPlan/{planid}")
    public R getPlan(@PathVariable("planid") Long planid)
    {
        String memberid = ServletUtils.getRequest().getHeader(Constants.CURRENT_ID);

        VerifyPlanInfo fatherverifyPlanInfo = verifyPlanInfoService.selectVerifyPlanInfoById(planid);
        List<VerifyPlanInfo> verifyPlanInfos = verifyPlanInfoService.selectVerifyPlanInfoByParentId(planid);

        //返回操作权限
        List<VerifyPlanInfos> sonverifyPlanInfoList = verifyPlanInfos.stream().map(vpi -> {
            String operation = "Read";
            if (vpi.getStatus() == 0 && ifhaveauthority(vpi.getPlanid())) {  //只有组长或者管理员可以编辑未发布的计划
                operation = "Writed";
                fatherverifyPlanInfo.setOperation(operation);
            }
            vpi.setOperation(operation);
            if (vpi.getSupplycategory() != null) {
                vpi.setSupplycategorys(vpi.getSupplycategory().split(","));
            }
            VerifyQuestionnaire verifyQuestionnaire = new VerifyQuestionnaire();
            verifyQuestionnaire.setVendorname(vpi.getSuppliername());
            verifyQuestionnaire.setPlanid(vpi.getPlanid().toString());
            verifyQuestionnaire.setLoguser(memberid);

            //给前台返回提交状态
            if (vpi.getGlobalcommit().equals(1l)) {
                vpi.setCurrentcommited("已提交");
            } else {
                if (verifyTemplateContentService.checkCommit(verifyQuestionnaire)) {
                    vpi.setCurrentcommited("已提交");

                } else {
                    vpi.setCurrentcommited("未提交");
                }
            }

            //设置审核时间传给前台
            String[] verifytime = new String[2];
            if(StringUtils.isNotEmpty(vpi.getVerifystarttime())){
                verifytime[0]=vpi.getVerifystarttime();
            }
            if(StringUtils.isNotEmpty(vpi.getVerifyendtime())){
                verifytime[1]=vpi.getVerifyendtime();
            }
            vpi.setVerifytime(verifytime);

            //返回成员信息
            List<VerifyPlanInfos.innerVerify> vpmm = verifyMemberInfoService.selectVerifyMemberInfoByPlanid(vpi);
//            List<VerifyMemberInfo> verifyMemberInfos = verifyMemberInfoService.selectVerifyMemberInfoByPlanid(vpi.getPlanid());
//            List<VerifyPlanInfos.innerVerify> vpmm = verifyMemberInfos.stream().map(vmi -> {
//                List<String> moudles = Arrays.asList(vmi.getMoudlecode().split(","));
//                List<VerifyTemplate> verifyTemplates = null;
//                List<VerifyTemplate> son_Ep6 = null;
//                List<VerifyTemplate> Ep6 = null;
//
//                //VDA6.3 删除P6的子模块列表
//                if(vpi.getVerifytype().contains("VDA6.3")){
//                    verifyTemplates = verifyTemplateService.selectVerifyTemplateClassNew(vpi.getVerifytype(),vpi.getFactorycode());
//                    son_Ep6 = verifyTemplates.stream().filter(v -> v.getContent().startsWith("6.")).collect(Collectors.toList());
//                    List<String> ep6_verify_list = son_Ep6.stream().map(s -> s.getVerifyid()).collect(Collectors.toList());
//                    String ep6_string_list = StringUtils.join(ep6_verify_list, ",");
//                    Ep6 = verifyTemplates.stream().filter(v -> v.getContent().startsWith("6、")).collect(Collectors.toList());
//
//                    if(Ep6!=null && Ep6.size()>0){
//                        if(vmi.getMoudlecode().contains(Ep6.get(0).getVerifyid())){
//                            moudles = moudles.stream().filter(m -> !ep6_string_list.contains(m)).collect(Collectors.toList());
//                        }
//                    }
//
//                }
//
//                if (vpi.getGroupleaderid() != null) {
//                    if (vpi.getGroupleaderid().equals(vmi.getMemberid())) {
//                        vmi.setIsGroupLeader("1");
//                    } else {
//                        vmi.setIsGroupLeader("0");
//                    }
//                }
//                VerifyPlanInfos.innerVerify innerVerify = new VerifyPlanInfos.innerVerify(vmi.getPlanid(), vmi.getMemberid(), moudles, vmi.getMembername(), vmi.getPhonenumber(), vmi.getJobnumber(), vmi.getJobunit(), vmi.getPosition(), vmi.getIsGroupLeader());
//                return innerVerify;
//            }).collect(Collectors.toList());

            VerifyPlanInfos sonverifyPlanInfo = new VerifyPlanInfos();
            List<VerifyTemplate> verifyTemplates = verifyTemplateService.selectHistoryVerifyTemplateClassByPlanid(vpi.getPlanid());
            sonverifyPlanInfo.setVpi(vpi);
            sonverifyPlanInfo.setVpmm(vpmm);
            sonverifyPlanInfo.setVerifyTemplates(verifyTemplates);
            return sonverifyPlanInfo;
        }).collect(Collectors.toList());
        Map<String,Object> map = new HashMap<>();
        map.put("verifyPlanInfo",fatherverifyPlanInfo);
        map.put("verifyPlanInfos",sonverifyPlanInfoList);

        return resultMap(map);
    }



    /**
     * 保存当前计划页内计划
     *
     * 2020/11/11
     */
    @PostMapping("saveverifyplan")
    public R saveVerifyPlanss(@RequestBody Map<String,Object> stringObjectMap){

        Long mainplanid = null;
        try {
            mainplanid = verifyPlanInfoService.saveCurrentPlanInfo(stringObjectMap);
        } catch (Exception e) {
            return R.error(505,e.getMessage());
        }
        Map<String,Object> map = new HashMap<>();
        map.put("planid",mainplanid);
        return resultMap(map);
    }






}
